<template>
  <div class="container">
    <div class="operating" v-if="whiteboardData.content">
      <el-button @click="pageNo-=1" :disabled="pageNo===1">上一页</el-button>
      <span>{{ pageNo }} / {{ whiteboardData.content.length }}</span>
      <el-button @click="pageNo+=1" :disabled="pageNo===whiteboardData.content.length">下一页</el-button>
      <el-button type="primary" @click="gotoLogin">前往登录</el-button>
    </div>
    <div v-if="whiteboardData.content" class="show-area" @click="hint">
      <img :src="curImgData" width="100%" height="100%">
    </div>
  </div>
</template>

<script>
export default {
  name: "Share",
  data() {
    return {
      user_id: 'guest', // 访客id
      whiteboard_id: this.$route.query.whiteboard_id, // 白板id，从路由中获取
      whiteboardData: {}, // 白板数据
      socket: null, // socket
      pageNo: 1,
    }
  },
  created() {
    this.init();// 建立websocket连接
  },
  methods: {
    init() {
      let path = `ws://1.14.14.93:3000/whiteboard/connect?user_id=${this.user_id}&whiteboard_id=${this.whiteboard_id}`;
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.addEventListener("message", this.getMessage);
      }
    },
    getMessage({data}) {
      let whiteboard = JSON.parse(data);
      if (whiteboard.content) {
        // 收到的广播消息
        this.whiteboardData.content = whiteboard.content;
      } else {
        // 刚建立收到的消息
        this.whiteboardData = whiteboard.data;
      }
    },
    open() {
      console.log('ws连接建立成功')
    },
    error() {
      console.log('ws连接出错')
    },
    // 跳转登录页
    gotoLogin() {
      this.socket.close(); // 关闭ws连接
      this.$router.push({
        path: '/',
        query: {redirectTo: 'palatte', whiteboard_id: this.whiteboard_id,state:this.whiteboardData.readOnly}
      })
    },
    // 提示信息
    hint() {
      this.$message("需要登录才可以操作")
    }
  },
  computed: {
    // 根据当前页数返回要显示的画面
    curImgData() {
      return this.whiteboardData.content[this.pageNo - 1];
    }
  }
}
</script>

<style scoped lang="less">
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;

  .operating {
    padding: 10px;
  }

  .show-area {
    width: 100%;
    height: calc(100% - 60px);
  }
}
</style>